package com.moli.iov.down.command.mq.kafka.handle;

import com.alibaba.fastjson.JSONObject;
import com.moli.iov.down.enums.command.CommandEnum;
import com.moli.iov.protocol.codec.DataWrapper;
import com.moli.iov.util.ByteArrayUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * <p>
 *  kafka 消费者 下发协议 终端响应业处理 handle
 * </p>
 *
 * @author: zql
 * @Date: 2018/11/30 14:29
 */
@Component
public class KafkaMessageHandler {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${kafka.down.reponse.topic}")
    private String kafkaDownReponsTopic;
    @Value("${kafka.down.getway.reponse.topic}")
    private String kafkaDownGetwayReponseTopic;

    @Autowired
    private GatewayHandler gatewayHandler;

    @Autowired
    private ResponseHandle responseHandle;

    /**
     * 业务处理
     * @param vin
     * @param dataWrapper
     */
    public void handle(String topic, String vin, DataWrapper dataWrapper){
        String dataWrapperStr = JSONObject.toJSONString(dataWrapper);
        logger.info("业务处理 topic:{} vin:{} dataWrapper:{}", topic, vin, dataWrapperStr);
        if(kafkaDownReponsTopic.equals(topic)){
            String allDataStr = ByteArrayUtil.toHexString(dataWrapper.getAllData());
            logger.info("业务处理 普通处理 vin:{} data:{}", vin, allDataStr);
            //终端响应Handle
            responseHandle.responseHandle(vin, dataWrapper.getAllData());

        }else if(kafkaDownGetwayReponseTopic.equals(topic)){
            logger.info("终端响应， 网关已下发命令 vin:{}， dataWrapper：{}", vin, dataWrapperStr);
            if(dataWrapper.getCommand() == null ||
                CommandEnum.isUpdate(dataWrapper.getCommand())){
                //网关响应handle(网关已下发命令，终端未响应)
                gatewayHandler.gatewayHandle(vin, dataWrapper);
            }
        }else{
            logger.info("业务处理 无处理器 vin:{}", vin);
        }
    }

}
